package com.yulian.web_api.supplier_management;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.healthmarketscience.sqlbuilder.CustomSql;
import com.healthmarketscience.sqlbuilder.InCondition;
import com.healthmarketscience.sqlbuilder.SelectQuery;
import com.yulian.repository.CommonRepositoryImpl;
import com.yulian.util.CommonUtils; 

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.Tuple;

/**
 * 该类位于业务逻辑层，主要实现 商品比价参数设置 数据查询，新增数据，更新数据数据的业务逻辑，为MainVerticle中的REST接口提供服务
 *
 * @author 汪俊峰 刘涛 余大勇
 */
public class GoodsPriceBidParameterManager {
    final InternalLogger logger = Log4JLoggerFactory.getInstance(GoodsPriceBidParameterManager.class);
    CommonRepositoryImpl commonRepository = new CommonRepositoryImpl();

    /**
     * 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecords(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        /**
 		 *  获取bodyJSObj参数对象中字段的值,各字段注释请参看数据库设计文档中数据表goods_price_bid_parameter的说明
			goods_gather_area_id	供应链商品聚集区编码
			site_id	销售地区编码
			standard_freight_price	比价标准运费斤价，从地图系统同步，参看表transport_unit_price中字段 standard_price
			class_lv1_id	商品一级分类编码
			class_lv2_id	商品小二分类编码
			variety_id	品种编码
			aggregation_id	聚合商品编码
			aggregation_name	聚合商品名
			supplier_profit_rate	供应商利润率
			maximum_rate	最低比率
			minmum_rate	最高比率 
 		 */
        // 验证必须传递的字段
        List<String> must_fields = Arrays.asList("goods_gather_area_id_list", "site_id_list", "class_lv1_id_list", "class_lv2_id_list", "variety_id_list", "aggregation_id_list", "is_delete_list");
        JsonObject must = this.commonRepository.verifyAllParamMust(bodyJSObj, must_fields);
        if (must != null) {
            promise.complete(must);
            return promise.future();
        }
        // 验证必须传的数值字段
 		List<String>  numeric_fields = Arrays.asList( "page_size", "page_index");
 		JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
 		if (numeric != null) {
 			promise.complete(numeric);  
 			return promise.future();
 		}
        
        //从bodyJson中获取数据   各字段注释请参看数据库设计文档中数据表goods_price_bid_parameter的说明
        String goods_gather_area_id_list = bodyJSObj.getString("goods_gather_area_id_list");
        String site_id_list = bodyJSObj.getString("site_id_list");
        String class_lv1_id_list = bodyJSObj.getString("class_lv1_id_list");
        String class_lv2_id_list = bodyJSObj.getString("class_lv2_id_list");
        String variety_id_list = bodyJSObj.getString("variety_id_list");
        String aggregation_id_list = bodyJSObj.getString("aggregation_id_list");
        String is_delete_list = bodyJSObj.getString("is_delete_list");
        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size; 
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();
        queryJSObj.put("goods_gather_area_id", goods_gather_area_id_list);
        queryJSObj.put("site_id", site_id_list);
        queryJSObj.put("class_lv1_id", class_lv1_id_list);
        queryJSObj.put("class_lv2_id", class_lv2_id_list);
        queryJSObj.put("variety_id", variety_id_list);
        queryJSObj.put("aggregation_id", aggregation_id_list);
        queryJSObj.put("is_delete", is_delete_list);

        //定义多个set，存储每一个 goods_price_bid_parameter中多个code
        Set<String> goods_gather_area_id_list_set = new HashSet<String>();
        Set<String> site_id_list_set = new HashSet<String>();
        Set<String> class_lv1_id_list_set = new HashSet<String>();
        Set<String> class_lv2_id_list_set = new HashSet<String>();
        Set<String> variety_id_list_set = new HashSet<String>();
        Set<String> aggregation_id_list_set = new HashSet<String>();
        this.commonRepository.getCon(client).onSuccess(conn -> {
            String sql = createSelectSql(queryJSObj, query_offset, query_limit);
            this.commonRepository.queryJsonArray(conn, sql, "getPriceBidParameterRecords")
            .onSuccess(resJSArray -> {
                //取出每条记录中含code字段的值放入对应的集合
                for (int i = 0; i < resJSArray.size(); i++) {
                    JsonObject jsonObj = resJSArray.getJsonObject(i);
                    goods_gather_area_id_list_set.add(jsonObj.getString("goods_gather_area_id"));
                    site_id_list_set.add(jsonObj.getString("site_id"));
                    class_lv1_id_list_set.add(jsonObj.getString("class_lv1_id"));
                    class_lv2_id_list_set.add(jsonObj.getString("class_lv2_id"));
                    variety_id_list_set.add(jsonObj.getString("variety_id"));
                    aggregation_id_list_set.add(jsonObj.getString("aggregation_id"));
                }

                //获取满足条件的记录总数
                String count_sql = this.commonRepository.createCountSql(queryJSObj, "goods_price_bid_parameter");
                Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "get_goods_price_bid_parameter");
                //获取供应链商品聚集区的编码和名称
                String goods_gather_area_sql = "select distinct id, goods_gather_area_name from goods_gather_area where id = any(array['" +
                String.join("','", goods_gather_area_id_list_set) + "']) ";
                Future<JsonObject> getGoodsGatherAreaNameFuture = this.commonRepository.getCodeNamePairJsonObject(conn, goods_gather_area_sql, "goods_gather_area_name");
                //获取比价销售地编码和名称
                String site_sql = "select distinct id,site_name from site where site_id = any(array['" +
                String.join("','", site_id_list_set) + "']) and is_delete=0";
                Future<JsonObject> getSiteFuture = this.commonRepository.getCodeNamePairJsonObject(conn, site_sql, "get_site_name");
                //获取商品一级分类编码和名称
                String class_lv1_sql = "select distinct id,class_name from goods_class_lv1 where id = any(array['" + String.join("','", class_lv1_id_list_set) + "']) and is_delete=0";
                Future<JsonObject> getClassLv1Future = this.commonRepository.getCodeNamePairJsonObject(conn, class_lv1_sql, "get_class_lv1_name");
                //获取小二分类编码和名称
                String class_lv2_sql = "select distinct id,class_name from goods_class_lv2 where id = any(array['" + String.join("','", class_lv2_id_list_set) + "']) and is_delete=0";
                Future<JsonObject> getClassLv2Future = this.commonRepository.getCodeNamePairJsonObject(conn, class_lv2_sql, "get_class_lv2_name");
                //获取品种编码和名称
                String variety_sql = "select distinct id,class_name from goods_variety where id = any(array['" + String.join("','", variety_id_list_set) + "']) and class_level=4 and is_delete=0";
                Future<JsonObject> getVarietyFuture = this.commonRepository.getCodeNamePairJsonObject(conn, variety_sql, "get_variety_name");
                //获取聚合商品编码和名称
                String aggregation_sql = "select distinct id, aggregation_name from  aggregation_goods where id = any(array['" +
                String.join("','", aggregation_id_list_set) + "']) ";
                Future<JsonObject> getAggregationFuture = this.commonRepository.getCodeNamePairJsonObject(conn, aggregation_sql, "get_aggregation_name");

                CompositeFuture.join(Arrays.asList(getTotalFuture, getGoodsGatherAreaNameFuture, getSiteFuture, getClassLv1Future, getClassLv2Future, getVarietyFuture, getAggregationFuture)).onComplete(ar2 -> {
                    if (ar2.succeeded()) {
                        JsonObject goods_gather_area_info = new JsonObject();
                        JsonObject site_info = new JsonObject();
                        JsonObject class_lv1_info = new JsonObject();
                        JsonObject class_lv2_info = new JsonObject();
                        JsonObject variety_info = new JsonObject();
                        JsonObject aggregation_info = new JsonObject();

                        int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                        goods_gather_area_info = (JsonObject) ar2.result().list().get(1);
                        site_info = (JsonObject) ar2.result().list().get(2);
                        class_lv1_info = (JsonObject) ar2.result().list().get(3);
                        class_lv2_info = (JsonObject) ar2.result().list().get(4);
                        variety_info = (JsonObject) ar2.result().list().get(5);
                        aggregation_info = (JsonObject) ar2.result().list().get(6); 
                        //从配置文件中读取
                        JsonObject is_delete_info = config.getJsonObject("DELETE_INFO"); 
                        // 最后组装含有name的Json对象和数组
                        JsonArray recordsJSArray = new JsonArray();
                        for (int i = 0; i < resJSArray.size(); i++) {
                            JsonObject record_obj = resJSArray.getJsonObject(i);
                            String goods_gather_area_id = record_obj.getString("goods_gather_area_id");
                            record_obj.put("goods_gather_area_name", goods_gather_area_info.getString(goods_gather_area_id));

                            String site_id = record_obj.getString("site_id");
                            record_obj.put("site_name", site_info.getString(site_id));

                            String class_lv1_id = record_obj.getString("class_lv1_id");
                            record_obj.put("class_lv1_name", class_lv1_info.getString(class_lv1_id));

                            String class_lv2_id = record_obj.getString("class_lv2_id");
                            record_obj.put("class_lv2_name", class_lv2_info.getString(class_lv2_id));

                            String variety_id = record_obj.getString("variety_id");
                            record_obj.put("variety_name", variety_info.getString(variety_id));

                            String aggregation_id = record_obj.getString("aggregation_id");
                            record_obj.put("aggregation_name", aggregation_info.getString(aggregation_id));

                            record_obj.put("is_delete_name", is_delete_info.getString(record_obj.getString("is_delete")));
                            recordsJSArray.add(record_obj);
                        }
                        JsonObject dataJSObj = new JsonObject();
                        dataJSObj.put("total", total_records).put("records", recordsJSArray);
                        responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);

                        promise.complete(responseJSObj);
                    } else {
                        logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                        promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getPriceBidParameterRecords", "获取品种商品比价基础参数用失败"));
                    }
                });
            }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "getPriceBidParameterRecords", "获取品种商品比价基础参数用失败")));
        }).onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getPriceBidParameterRecords", "数据库连接失败")));

        return promise.future();
    }

    /**
     * 创建查询符合搜索条件记录的sql语句
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSql(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("goods_gather_area_id"), new CustomSql("site_id"), new CustomSql("standard_freight_price"),
        new CustomSql("class_lv1_id"), new CustomSql("class_lv2_id"), new CustomSql("variety_id"),
        new CustomSql("aggregation_id"), new CustomSql("aggregation_name"), new CustomSql("supplier_profit_rate"), new CustomSql("maximum_rate"), new CustomSql("minmum_rate"),
        new CustomSql("is_delete"), new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("goods_price_bid_parameter");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where  InCondtion 子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }


    /**
     * 该方法实现接收web前端通过body传入的参数，调用数据访问层CommonParameterRepositoryImpl 类的方法实现数据的增、改。
     * 通过含参数的Json对象bodyJSObj，通过method字段获取操作类型，分别是insert，update
     * 1) 操作类型为 insert，新增数据
     * 2）操作类型为 update，更新数据 
     * 调用GoodsPriceBidParameterRepositoryImpl 的方法
     *
     * @param client
     * @param bodyJSObj
     * @param user
     * @return
     */
    public Future<JsonObject> insertOrUpdate(PgPool client, JsonObject bodyJSObj, User user) {
        Promise<JsonObject> promise = Promise.promise();
        int user_id = user.attributes().getJsonObject("accessToken").getInteger("userId");
        String create_user = user.attributes().getJsonObject("accessToken").getString("username");
        
        // 验证必须传递的字段
        List<String> must_fields = Arrays.asList("method", "goods_gather_area_id", "site_id", "class_lv1_id", "class_lv2_id",
        "variety_id", "aggregation_id");
        JsonObject must = this.commonRepository.verifyAllParamMust(bodyJSObj, must_fields);
        if (must != null) {
            promise.complete(must);
            return promise.future();
        } 
        // 验证数值字段
 		List<String>  numeric_fields = Arrays.asList( "supplier_profit_rate", "maximum_rate", "minmum_rate", "id");
 		JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
 		if (numeric != null) {
 			promise.complete(numeric);  
 			return promise.future();
 		} 
 		/**
 		 *  获取bodyJSObj参数对象中字段的值,各字段注释请参看数据库设计文档中数据表goods_price_bid_parameter的说明
			goods_gather_area_id	供应链商品聚集区编码
			site_id	销售地区编码
			standard_freight_price	比价标准运费斤价，从地图系统同步，参看表transport_unit_price中字段 standard_price
			class_lv1_id	商品一级分类编码
			class_lv2_id	商品小二分类编码
			variety_id	品种编码
			aggregation_id	聚合商品编码
			aggregation_name	聚合商品名
			supplier_profit_rate	供应商利润率
			maximum_rate	最低比率
			minmum_rate	最高比率 
 		 */
        //获取操作类型字段的值
        String method = bodyJSObj.getString("method"); 
        Long goods_gather_area_id = bodyJSObj.getLong("goods_gather_area_id");
        Long site_id = bodyJSObj.getLong("site_id");
        Long class_lv1_id = bodyJSObj.getLong("class_lv1_id");
        Long class_lv2_id = bodyJSObj.getLong("class_lv2_id");
        Long variety_id = bodyJSObj.getLong("variety_id");
        Long aggregation_id = bodyJSObj.getLong("aggregation_id");
        Double supplier_profit_rate = bodyJSObj.getDouble("supplier_profit_rate");
        Double maximum_rate = bodyJSObj.getDouble("maximum_rate");
        Double minmum_rate = bodyJSObj.getDouble("minmum_rate");
        // 获取bodyJSObj参数对象中字段的值
        long id = Long.valueOf(bodyJSObj.getString("id"));
        
        this.commonRepository.getCon(client).onSuccess(conn -> {
            /**
             * 校验多个code是否合法
             */
            //从transport_unit_price表中读取的字段
            String get_standard_freight_price_sql = "select standard_freight_price from transport_unit_price where class_lv1_id = $1 and is_delete = 0 limit 1";
            Future<JsonObject> getStandardFreightPrice = this.commonRepository.queryOneJsonObject(conn, get_standard_freight_price_sql, Tuple.of(class_lv1_id), "get_standard_freight_price_sql", "获取比价标准运费斤价 操作失败");
            //校验供应链商品聚集区code
            String goods_gather_area_id_sql = "select id, goods_gather_area_name from goods_gather_area where id = $1 and is_delete = 0 limit 1";
            Future<JsonObject> goodsGatherAreaCodeFuture = this.commonRepository.queryOneJsonObjectThrow(conn, goods_gather_area_id_sql, Tuple.of(goods_gather_area_id), "insert_goods_price_bid_parameter", "应链商品聚集区code 操作失败");
            //校验销售地区code
            String site_id_sql = "select id, site_name from site where id = $1 and is_delete = 0 limit 1";
            Future<JsonObject> siteCodeFuture = this.commonRepository.queryOneJsonObjectThrow(conn, site_id_sql, Tuple.of(site_id), "insert_goods_price_bid_parameter", "销售地区code 操作失败");
            //校验商品一级分类code
            String class_lv1_id_sql = "select id, class_name from goods_class_lv1 where id = $1 and is_delete = 0 limit 1";
            Future<JsonObject> classLv1CodeFuture = this.commonRepository.queryOneJsonObjectThrow(conn, class_lv1_id_sql, Tuple.of(class_lv1_id), "insert_goods_price_bid_parameter", "商品一级分类code 操作失败");
            //校验商品小二分类code
            String class_lv2_id_sql = "select id, class_name from goods_class_lv2 where id = $1 and is_delete = 0 limit 1";
            Future<JsonObject> classLv2CodeFuture = this.commonRepository.queryOneJsonObjectThrow(conn, class_lv2_id_sql, Tuple.of(class_lv2_id), "insert_goods_price_bid_parameter", "商品小二分类code 操作失败");
            //校验商品品种code
            String variety_id_sql = "select id, class_name from goods_variety where id = $1 and is_delete = 0 limit 1";
            Future<JsonObject> varietyCodeFuture = this.commonRepository.queryOneJsonObjectThrow(conn, variety_id_sql, Tuple.of(variety_id), "insert_goods_price_bid_parameter", "商品品种code 操作失败");
            //校验聚合商品code
            String aggregation_id_sql = "select  id, aggregation_name from id where id = $1 and is_delete = 0 limit 1";
            Future<JsonObject> aggregationCodeFuture = this.commonRepository.queryOneJsonObjectThrow(conn, aggregation_id_sql, Tuple.of(aggregation_id), "insert_goods_price_bid_parameter", "聚合商品code 操作失败");
 
            if (method.equals("insert")) {
                //判断插入的数据是否已经存在
                String goods_price_bid_parameter_sql = "select count(*) as total from goods_price_bid_parameter where goods_gather_area_id = $1 and site_id = $2 and aggregation_id = $3";
                Future<Integer> goodsGatherAreaCodesiteCodeaggregateCodeFuture = this.commonRepository.getRecordsCount(conn, goods_price_bid_parameter_sql, Tuple.of(goods_gather_area_id, site_id, aggregation_id), "insert_goods_price_bid_parameter");
                // 并行执行多个future
                CompositeFuture.join(Arrays.asList(goodsGatherAreaCodesiteCodeaggregateCodeFuture, getStandardFreightPrice, goodsGatherAreaCodeFuture, siteCodeFuture, classLv1CodeFuture, classLv2CodeFuture, varietyCodeFuture, aggregationCodeFuture))
                .onComplete(ar -> {
                    if (ar.succeeded()) {
                        int total_records = Integer.valueOf(ar.result().list().get(0).toString());
                        //standard_freight_price 通过返回参数值的Json对象去获取
                        JsonObject goods_value = (JsonObject) ar.result().list().get(1);
                        double standard_freight_price = 0;
                        if (goods_value.getValue("standard_freight_price") != null && !goods_value.getValue("standard_freight_price").equals(""))
                            standard_freight_price = Double.valueOf(goods_value.getString("standard_freight_price")); 
                        if (total_records == 0) {
                            // 新增
                            String insert_sql = "INSERT INTO goods_price_bid_parameter(goods_gather_area_id,site_id,standard_freight_price,class_lv1_id," +
                            "class_lv2_id,variety_id, aggregation_id, supplier_profit_rate,maximum_rate,minmum_rate,create_user)" +
                            " VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)  RETURNING id";
                            this.commonRepository.insertOrUpdate(conn, insert_sql, Tuple.of(goods_gather_area_id, site_id, standard_freight_price, class_lv1_id,
                            class_lv2_id, variety_id, aggregation_id, supplier_profit_rate, maximum_rate, minmum_rate, user_id), "insert_goods_price_bid_parameter","新增品种商品比价基础参数")
                            .onSuccess(resultJSObj -> {  
                                //写入操作日志
                                this.commonRepository.writePlatformLog(conn, user_id,"新增", "goods_price_bid_parameter/insert", bodyJSObj, resultJSObj, "")
                                .onComplete(ar3 -> {
                                    promise.complete(resultJSObj);
                                });
                            }).onFailure(err -> promise.fail(CommonUtils.createExceptionJsonObjectStr(err, "insertGoodsPriceBidParameter", "新增品种商品比价基础参数基本信息失败"))); 
                        } else {
                            // 更新
                            String update_sql = "update goods_price_bid_parameter set goods_gather_area_id = $1, site_id = $2,standard_freight_price=, $3,class_lv1_id = $4, class_lv2_id = $5, variety_id = $6, aggregation_id = $7, " +
                            "supplier_profit_rate= $8,maximum_rate= $9,minmum_rate= $10,update_user = $11 WHERE goods_gather_area_id = $12 and site_id = $13 and aggregation_id = $14 RETURNING id";
                            this.commonRepository.insertOrUpdate(conn, update_sql, Tuple.of(goods_gather_area_id, site_id, standard_freight_price, class_lv1_id, class_lv2_id, variety_id,
                            aggregation_id, supplier_profit_rate, maximum_rate, minmum_rate, user_id, goods_gather_area_id, site_id, aggregation_id), "update_goods_price_bid_parameter","更新品种商品比价基础参数")
                            .onSuccess(resultJSObj -> {  
                                //写入操作日志
                                this.commonRepository.writePlatformLog(conn, user_id,"编辑", "goods_price_bid_parameter/insert", bodyJSObj, resultJSObj, "")
                                .onComplete(ar3 -> {
                                    promise.complete(resultJSObj);
                                });
                            }).onFailure(err -> promise.fail(CommonUtils.createExceptionJsonObjectStr(err, "insertGoodsPriceBidParameter", "新增品种商品比价基础参数基本信息失败")));

                        }
                    } else {
                        promise.fail(CommonUtils.createExceptionJsonObjectStr(ar, "insertGoodsPriceBidParameter", "新增数据发生错误"));
                    }
                });
            } else if (method.equals("update")) {
                // 并行执行多个future
                CompositeFuture.join(Arrays.asList(getStandardFreightPrice, goodsGatherAreaCodeFuture, siteCodeFuture, classLv1CodeFuture, classLv2CodeFuture, varietyCodeFuture, aggregationCodeFuture))
                .onComplete(ar -> {
                    if (ar.succeeded()) {
                        //standard_freight_price 通过返回参数值的Json对象去获取
                        JsonObject goods_value = (JsonObject) ar.result().list().get(0);
                        double standard_freight_price = 0;
                        if (goods_value.getValue("standard_freight_price") != null && !goods_value.getValue("standard_freight_price").equals(""))
                            standard_freight_price = Double.valueOf(goods_value.getString("standard_freight_price")); 
                        String update_sql = "UPDATE goods_price_bid_parameter SET supplier_profit_rate= $1,maximum_rate= $2,minmum_rate= $3, standard_freight_price = $4, update_user=$5 WHERE id = $6 RETURNING id";
                        this.commonRepository.insertOrUpdate(conn, update_sql, Tuple.of(supplier_profit_rate, maximum_rate, minmum_rate, standard_freight_price, user_id, id), "update_goods_price_bid_parameter","更新品种商品比价基础参数")
                        .onSuccess(resultJSObj -> {  
                            //写入操作日志
                            this.commonRepository.writePlatformLog(conn, user_id,"编辑", "/web/goods_price_bid_parameter/update", bodyJSObj, resultJSObj, "")
                            .onComplete(ar3 -> {
                                 promise.complete(resultJSObj);
                            });
                        }).onFailure(err -> promise.fail(CommonUtils.createExceptionJsonObjectStr(err, "updateGoodsPriceBidParameter", "更新品种商品比价基础参数失败"))); 
                    } else {
                        promise.fail(CommonUtils.createExceptionJsonObjectStr(ar, "updateGoodsPriceBidParameter", "更新数据发生错误"));
                    }
                });
            }
        }).onFailure(err -> promise.fail(CommonUtils.createExceptionJsonObjectStr(err, "getGoodsPriceBidParameterRecords", "数据库连接失败")));
        return promise.future();
    }
}
     
